const h = (tag, props, children) => {
  return {
    tag,
    props,
    children
  }
}


const mount = (vnode, container) => {
  console.log(container)
  // 1。创建真实的元素并且在VNODE上保存el
  const el = vnode.el = document.createElement(vnode.tag)

  // 2.处理props
  if (vnode.props) {
    for (const key in vnode.props) {
      const value = vnode.props[key]
      if (key.startsWith('on')) {
        el.addEventListener(key.slice(2).toLowerCase(), value)
      } else {
        el.setAttribute(key, value)
      }
     
    }
  }

  // 3.处理children
  if (vnode.children) {
    if (typeof vnode.children === 'string') {
      el.textContent = vnode.children
    } else {
      vnode.children.forEach(item => {
        mount(item, el)
      })
    }
  }

  // 4.挂载
  container.appendChild(el)
}


const patch = (n1, n2) => {
  console.log(n1, n2)
  if (n1.tag !== n2.tag) {
    const elParent = n1.el.parentElement;
    elParent.removeChild(n1.el)
    mount(n2, elParent)
  } else {
    // 取出el对象，并在n2中进行保存
    const el = n2.el = n1.el
    // 处理props
    const oldProps = n1.props || {}
    const newProps = n2.props || {}
    for (const key in newProps ) {
      const oldValue = oldProps[key]
      const newValue = newProps[key]
      if (newValue !== oldValue) {
        if (key.startsWith('on')) {
          el.addEventListener(key.slice(2).toLowerCase(), newValue)
        } else {
          el.setAttribute(key, newValue)
        }
      }
    }

    // 删除旧props
    for (const key in oldProps) {
      const value = oldProps[key]
      if (key.startsWith('on')) {
        el.removeEventListener(key.slice(2).toLowerCase(), value)
      }
      if (!(key in newProps)) {
          el.removeAttribute(key, value)
      }
    }

    // 处理children
    const odlChildren = n1.children || []
    const newChildren = n2.children || []
    if (typeof odlChildren === 'string') {
      if (typeof newChildren === 'string') {
        if (newChildren !== odlChildren) {
          el.textContent = newChildren
        }
      }

     
    }
    else { // 情况二： newchildren本身就是一个数组
      if (typeof odlChildren === 'string') {
        el.innerHTML = ''
        newChildren.forEach(item => {
          mount(item, el)
        })
      } else {
        // odlChildren: [v1, v2, v5, v6]  多出来的删除
        // newChildren: [v1, v2, v3] 多出来的添加
        const monnetLength = Math.min(newChildren.length, odlChildren.length)
        for( let i = 0; i < monnetLength; i++ ) {
          patch(odlChildren[i], newChildren[i])
        }

        if (newChildren.length > odlChildren.length) {
          newChildren.slice(odlChildren.length).forEach(item => {
            mount(item, el)
          })
        }
        if (odlChildren.length < newChildren.length) {
          odlChildren.slice(newChildren.length).forEach(item => {
            el.removeAttribute(item.el)
          })
        }
      }
    }
  }
}